from lxml import etree

from request import http
from store.book import Book, BookStatus
from store.chapter import Chapter


def get_book(id):
    book = Book()
    book.url = f"https://nzg.readggg.com/indexs/{id}/"
    book.page_source = http.get(book.url)
    dom = etree.HTML(book.page_source)
    book.name = dom.xpath('//*[@id="top"]/span')[0].text
    book.author = get_book_author(dom)
    book.status = get_book_status(dom)
    book.description = dom.xpath('//*[@class="review"]/p')[0].text
    book.chapters = list_all_page_chapters(book.page_source)
    return book


def get_book_author(dom):
    author = dom.xpath('//*[@class="author"]')[0].text
    if author and author.startswith("作者："):
        author = author[3:]
    return author


def get_book_status(dom):
    status = dom.xpath('//*[@class="synopsisArea_detail"]//*[contains(text(), "状态")]')[0].text
    if status and status.startswith("状态："):
        status = status[3:]
    if status == "完结":
        return BookStatus.COMPLETED
    return BookStatus.UNKNOWN


def list_all_page_chapters(html):
    chapters = list_chapters(html)
    dom = etree.HTML(html)
    options = dom.xpath('//*[@id="indexselect"]/option[position() > 1]')
    for option in options:
        url = f"https://nzg.readggg.com/{option.attrib['value']}"
        html = http.get(url)
        chapters.extend(list_chapters(html))
    return chapters


def list_chapters(html):
    chapters = []
    dom = etree.HTML(html)
    nodes = dom.xpath("/html/body/div[5]/div[1]/p")
    for node in nodes:
        a = node.xpath("a")[0]
        chapter = Chapter()
        chapter.name = a.text
        chapter.url = f"https://nzg.readggg.com/{a.attrib['href']}"
        chapters.append(chapter)
    return chapters
